package at.codebase.db.dao;

import static at.codebase.db.OfyService.ofy;

import java.util.List;

import at.codebase.core.searchUser.UsernameSearch;
import at.codebase.db.entities.EUser;

/**
 * Provides static methods to manage users in the datastore.
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 * @author Daniel Marth <danielmarth@gmx.at>
 */
public class EUserDao {

	public static EUser getUserById(final Long userId) {
		if(userId.longValue() <= 0)
			return null;
		return ofy().load().type(EUser.class).id(userId.longValue()).get();
	}

	public static EUser getUserByGoogleId(final String googleUserId) {
		return ofy().load().type(EUser.class)
				.filter("googleUserId", googleUserId).first().get();
	}
	
	public static EUser getUserByMail(final String mail) {
		return ofy().load().type(EUser.class)
				.filter("userMail", mail).first().get();
	}

	public static void saveUser(final EUser userEntity) {
		ofy().save().entity(userEntity).now();
		UsernameSearch.putUser(userEntity);
	}

	public static List<EUser> getAllUsers() {
		return ofy().load().type(EUser.class).list();
	}

	public static void removeUser(final EUser userEntity) {
		UsernameSearch.dropUser(userEntity);
		ofy().delete().entity(userEntity);
	}

	public static List<EUser> getAdmins() {
		return ofy().load().type(EUser.class)
				.filter("isAdmin", new Boolean(true)).list();
	}
	/*
	public static void makeAdmin(final Long userId) {
		EUser user = getUserById(userId);
		user.setAdmin(true);
		ofy().save().entity(user).now();
	}
	*/

	public static void setActive(final Long userId, final boolean active) {
		EUser user = getUserById(userId);
		user.setActive(active);
		ofy().save().entity(user).now();
	}

	public static boolean duplicateUsername(String username) {
		return (ofy().load().type(EUser.class).filter("username", username).count() > 0);
	}

}
